<template>
  <div class="submit-review-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>提交与修订</h2>
        <!-- 返回主页按钮 -->
        <button @click="goToDashboard" class="btn btn-secondary" :class="{ 'mobile-btn': isMobile }">
          <i class="fa fa-home mr-2"></i>
          <span>{{ isMobile ? '首页' : '返回主页' }}</span>
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 待提交的合同 -->
    <div v-if="!loading && pendingContracts.length > 0" class="card mt-4">
      <div class="card-header bg-primary text-white">
        <h3>待提交的合同</h3>
      </div>
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table table-bordered table-hover">
            <thead class="bg-light">
            <tr>
              <th>合同ID</th>
              <th>合同名称</th>
              <th>客户</th>
              <th :class="{ 'd-none': isMobile }">创建时间</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in pendingContracts" :key="contract.id">
              <td>{{ contract.id }}</td>
              <td>{{ contract.name }}</td>
              <td>{{ contract.customerCompanyName || '未选择' }}</td>
              <td :class="{ 'd-none': isMobile }">{{ formatDate(contract.createTime) }}</td>
              <td class="operation-cell">
                <!-- 提交审核按钮 -->
                <button
                    @click="submitForReview(contract.id)"
                    class="btn btn-submit"
                    :disabled="!isProjectManager"
                    :class="{ 'mobile-btn': isMobile }"
                >
                  <i class="fa fa-paper-plane mr-1"></i>
                  <span>{{ isMobile ? '提交' : '提交审核' }}</span>
                </button>
                <!-- 查看详情按钮 -->
                <button @click="viewContract(contract.id)" class="btn btn-view" :class="{ 'mobile-btn': isMobile }">
                  <i class="fa fa-eye mr-1"></i>
                  <span>{{ isMobile ? '查看' : '查看详情' }}</span>
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件（含跳转功能） -->
        <div class="pagination mt-3 d-flex justify-content-between flex-wrap gap-2">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalPending }} 条
          </div>
          <div class="pagination-controls d-flex align-items-center gap-3">
            <!-- 分页按钮 -->
            <div class="pagination-buttons d-flex align-items-center">
              <button
                  @click="prevPendingPage"
                  :disabled="pendingCurrentPage === 0"
                  class="btn btn-page"
                  :class="{ 'mobile-btn': isMobile }"
              >
                <i class="fa fa-chevron-left"></i>
                <span :class="{ 'd-none': isMobile }"> 上一页</span>
              </button>
              <span class="page-info mx-2">
                第 {{ pendingCurrentPage + 1 }} / {{ pendingTotalPages }} 页
              </span>
              <button
                  @click="nextPendingPage"
                  :disabled="pendingCurrentPage === pendingTotalPages - 1"
                  class="btn btn-page"
                  :class="{ 'mobile-btn': isMobile }"
              >
                <span :class="{ 'd-none': isMobile }">下一页 </span>
                <i class="fa fa-chevron-right"></i>
              </button>
            </div>

            <!-- 页面跳转控件 -->
            <div class="page-jump d-flex align-items-center gap-2" :class="{ 'd-none': isMobile }">
              <span>跳至：</span>
              <input
                  type="number"
                  v-model.number="pendingJumpPage"
                  :min="1"
                  :max="pendingTotalPages"
                  class="form-control page-input"
                  @keyup.enter="handlePendingJump"
                  placeholder="页码"
              >
              <button
                  @click="handlePendingJump"
                  :disabled="!isPendingJumpValid"
                  class="btn btn-jump"
              >
                <i class="fa fa-arrow-right mr-1"></i>确认
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 待提交的合同为空 -->
    <div v-else-if="!loading && pendingContracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-check-circle text-success display-4 mb-3"></i>
          <h4>没有待提交的合同</h4>
          <p class="text-muted">您的所有合同都已提交审核或完成</p>
        </div>
      </div>
    </div>

    <!-- 待修订的合同 -->
    <div v-if="!loading && revisionContracts.length > 0" class="card mt-4">
      <div class="card-header bg-warning text-white">
        <h3>待修订的合同</h3>
      </div>
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table table-bordered table-hover">
            <thead class="bg-light">
            <tr>
              <th>合同ID</th>
              <th>合同名称</th>
              <th>客户</th>
              <th :class="{ 'd-none': isMobile }">需要修订原因</th>
              <th :class="{ 'd-none': isMobile }">最后修改时间</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in revisionContracts" :key="contract.id">
              <td>{{ contract.id }}</td>
              <td>{{ contract.name }}</td>
              <td>{{ contract.customerCompanyName || '未选择' }}</td>
              <td :class="{ 'd-none': isMobile }">{{ contract.revisionReason || '未提供具体原因' }}</td>
              <td :class="{ 'd-none': isMobile }">{{ formatDate(contract.updateTime) }}</td>
              <td class="operation-cell">
                <!-- 修订合同按钮 -->
                <button @click="editContract(contract.id)" class="btn btn-edit" :class="{ 'mobile-btn': isMobile }">
                  <i class="fa fa-edit mr-1"></i>
                  <span>{{ isMobile ? '修订' : '修订合同' }}</span>
                </button>
                <!-- 查看详情按钮 -->
                <button @click="viewContract(contract.id)" class="btn btn-view" :class="{ 'mobile-btn': isMobile }">
                  <i class="fa fa-eye mr-1"></i>
                  <span>{{ isMobile ? '查看' : '查看详情' }}</span>
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件（含跳转功能） -->
        <div class="pagination mt-3 d-flex justify-content-between flex-wrap gap-2">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalRevision }} 条
          </div>
          <div class="pagination-controls d-flex align-items-center gap-3">
            <!-- 分页按钮 -->
            <div class="pagination-buttons d-flex align-items-center">
              <button
                  @click="prevRevisionPage"
                  :disabled="revisionCurrentPage === 0"
                  class="btn btn-page"
                  :class="{ 'mobile-btn': isMobile }"
              >
                <i class="fa fa-chevron-left"></i>
                <span :class="{ 'd-none': isMobile }"> 上一页</span>
              </button>
              <span class="page-info mx-2">
                第 {{ revisionCurrentPage + 1 }} / {{ revisionTotalPages }} 页
              </span>
              <button
                  @click="nextRevisionPage"
                  :disabled="revisionCurrentPage === revisionTotalPages - 1"
                  class="btn btn-page"
                  :class="{ 'mobile-btn': isMobile }"
              >
                <span :class="{ 'd-none': isMobile }">下一页 </span>
                <i class="fa fa-chevron-right"></i>
              </button>
            </div>

            <!-- 页面跳转控件 -->
            <div class="page-jump d-flex align-items-center gap-2" :class="{ 'd-none': isMobile }">
              <span>跳至：</span>
              <input
                  type="number"
                  v-model.number="revisionJumpPage"
                  :min="1"
                  :max="revisionTotalPages"
                  class="form-control page-input"
                  @keyup.enter="handleRevisionJump"
                  placeholder="页码"
              >
              <button
                  @click="handleRevisionJump"
                  :disabled="!isRevisionJumpValid"
                  class="btn btn-jump"
              >
                <i class="fa fa-arrow-right mr-1"></i>确认
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 待修订的合同为空 -->
    <div v-else-if="!loading && revisionContracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-check-circle text-success display-4 mb-3"></i>
          <h4>没有待修订的合同</h4>
          <p class="text-muted">所有审核意见都已处理</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'SubmitReview',
  setup() {
    const store = useStore()
    const router = useRouter()

    // 新增：移动端判断（不影响原有方法）
    const isMobile = ref(window.innerWidth < 768)

    // 新增：窗口尺寸变化监听
    const handleResize = () => {
      isMobile.value = window.innerWidth < 768
    }

    // 基础状态管理（原有）
    const loading = ref(true)
    const errorMessage = ref('')
    const pageSize = ref(10)

    // 待提交合同相关（原有）
    const pendingContracts = ref([])
    const pendingCurrentPage = ref(0)
    const pendingTotalPages = ref(0)
    const totalPending = ref(0)
    const pendingJumpPage = ref(1)

    // 待修订合同相关（原有）
    const revisionContracts = ref([])
    const revisionCurrentPage = ref(0)
    const revisionTotalPages = ref(0)
    const totalRevision = ref(0)
    const revisionJumpPage = ref(1)

    // 用户信息（原有）
    const employeeId = ref(null)
    const employeePosition = ref(null)
    const isProjectManager = ref(false)

    // 待提交合同跳转验证（原有）
    const isPendingJumpValid = computed(() => {
      return Number.isInteger(pendingJumpPage.value) &&
          pendingJumpPage.value >= 1 &&
          pendingJumpPage.value <= pendingTotalPages.value &&
          pendingJumpPage.value !== pendingCurrentPage.value + 1
    })

    // 待修订合同跳转验证（原有）
    const isRevisionJumpValid = computed(() => {
      return Number.isInteger(revisionJumpPage.value) &&
          revisionJumpPage.value >= 1 &&
          revisionJumpPage.value <= revisionTotalPages.value &&
          revisionJumpPage.value !== revisionCurrentPage.value + 1
    })

    // 返回员工控制台（原有）
    const goToDashboard = () => {
      router.push('/employee/dashboard')
    }

    // 获取合同数据（原有）
    const fetchContracts = () => {
      loading.value = true
      errorMessage.value = ''

      if (!employeeId.value || !employeePosition.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      // 获取待提交合同
      axios.get('/auth/contracts/pending-submit', {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          page: pendingCurrentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            pendingContracts.value = response.data?.content || []
            pendingTotalPages.value = response.data?.totalPages || 1
            totalPending.value = response.data?.totalElements || 0
            pendingJumpPage.value = pendingCurrentPage.value + 1
          })
          .catch(error => {
            console.error('获取待提交合同失败', error)
            errorMessage.value = error.response?.status === 403
                ? '您没有权限查看待提交合同'
                : '获取待提交合同失败，请稍后再试'
          })

      // 获取待修订合同
      axios.get('/auth/contracts/pending-revision', {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          page: revisionCurrentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            revisionContracts.value = response.data?.content || []
            revisionTotalPages.value = response.data?.totalPages || 1
            totalRevision.value = response.data?.totalElements || 0
            revisionJumpPage.value = revisionCurrentPage.value + 1
          })
          .catch(error => {
            console.error('获取待修订合同失败', error)
            errorMessage.value = error.response?.status === 403
                ? '您没有权限查看待修订合同'
                : '获取待修订合同失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 提交合同进行审核（原有）
    const submitForReview = (contractId) => {
      if (!isProjectManager.value) {
        errorMessage.value = '只有项目经理有权限提交合同'
        return
      }

      if (!confirm('确定要提交这份合同进行审核吗？提交后将无法修改。')) {
        return
      }

      axios.put(`/auth/contracts/${contractId}/submit-review`, null, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        }
      })
          .then(() => {
            fetchContracts()
            alert('合同已成功提交审核！')
          })
          .catch(error => {
            console.error('提交合同失败', error)
            errorMessage.value = error.response?.data?.message || '提交合同失败，请稍后再试'
            alert(errorMessage.value)
          })
    }

    // 编辑合同（原有）
    const editContract = (contractId) => {
      router.push(`/contracts/${contractId}/edit`)
    }

    // 查看合同详情（原有）
    const viewContract = (contractId) => {
      router.push(`/contracts/${contractId}`)
    }

    // 待提交合同分页操作（原有）
    const prevPendingPage = () => {
      if (pendingCurrentPage.value > 0) {
        pendingCurrentPage.value--
        fetchContracts()
      }
    }

    const nextPendingPage = () => {
      if (pendingCurrentPage.value < pendingTotalPages.value - 1) {
        pendingCurrentPage.value++
        fetchContracts()
      }
    }

    // 待提交合同跳转处理（原有）
    const handlePendingJump = () => {
      if (!isPendingJumpValid.value) return
      pendingCurrentPage.value = pendingJumpPage.value - 1
      fetchContracts()
    }

    // 待修订合同分页操作（原有）
    const prevRevisionPage = () => {
      if (revisionCurrentPage.value > 0) {
        revisionCurrentPage.value--
        fetchContracts()
      }
    }

    const nextRevisionPage = () => {
      if (revisionCurrentPage.value < revisionTotalPages.value - 1) {
        revisionCurrentPage.value++
        fetchContracts()
      }
    }

    // 待修订合同跳转处理（原有）
    const handleRevisionJump = () => {
      if (!isRevisionJumpValid.value) return
      revisionCurrentPage.value = revisionJumpPage.value - 1
      fetchContracts()
    }

    // 格式化日期（原有）
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 初始化（原有逻辑 + 新增窗口监听）
    onMounted(() => {
      // 原有初始化逻辑
      employeeId.value = store.state.user?.id
      employeePosition.value = store.state.user?.position
      isProjectManager.value = store.state.user?.position === 'PROJECT_MANAGER'

      watch([
        () => store.state.user?.id,
        () => store.state.user?.position
      ], () => {
        employeeId.value = store.state.user?.id
        employeePosition.value = store.state.user?.position
        isProjectManager.value = store.state.user?.position === 'PROJECT_MANAGER'
        fetchContracts()
      })

      fetchContracts()

      // 新增：监听窗口尺寸变化
      window.addEventListener('resize', handleResize)
    })

    // 新增：组件卸载时移除监听
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
    })

    return {
      // 新增：移动端标识
      isMobile,
      // 原有返回值
      loading,
      errorMessage,
      pageSize,
      pendingContracts,
      pendingCurrentPage,
      pendingTotalPages,
      totalPending,
      pendingJumpPage,
      isPendingJumpValid,
      revisionContracts,
      revisionCurrentPage,
      revisionTotalPages,
      totalRevision,
      revisionJumpPage,
      isRevisionJumpValid,
      isProjectManager,
      goToDashboard,
      submitForReview,
      editContract,
      viewContract,
      prevPendingPage,
      nextPendingPage,
      prevRevisionPage,
      nextRevisionPage,
      handlePendingJump,
      handleRevisionJump,
      formatDate
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.submit-review-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn i {
  font-size: 14px;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  background-color: #6c757d;
  color: #fff;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

.btn-submit {
  background-color: #28a745;
  color: #fff;
}

.btn-submit:hover {
  background-color: #218838;
}

.btn-submit:disabled {
  background-color: #a3e0b1;
}

.btn-edit {
  background-color: #ffc107;
  color: #212529;
}

.btn-edit:hover {
  background-color: #e0a800;
}

.btn-view {
  background-color: #007bff;
  color: #fff;
  margin-left: 6px;
}

.btn-view:hover {
  background-color: #0069d9;
}

.btn-page {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #dee2e6;
  padding: 4px 10px;
}

.btn-page:hover {
  background-color: #e9ecef;
}

.btn-page:disabled {
  background-color: #f8f9fa;
  color: #adb5bd;
}

.btn-jump {
  background-color: #17a2b8;
  color: #fff;
}

.btn-jump:hover {
  background-color: #138496;
}

.btn-jump:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #0d6efd;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #dc3545;
  margin: 10px 0;
  padding: 12px 15px;
  background-color: #f8d7da;
  border-radius: 4px;
  display: flex;
  align-items: center;
  border-left: 3px solid #dc3545;
}

.card {
  margin-bottom: 20px;
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.card-header {
  padding: 12px 20px;
  font-weight: 600;
  font-size: 16px;
}

.card-body {
  padding: 20px;
}

.contracts-table {
  overflow-x: auto;
}

.table {
  width: 100%;
  margin-bottom: 0;
  border-collapse: separate;
  border-spacing: 0;
}

.table th,
.table td {
  padding: 12px 15px;
  vertical-align: middle;
  text-align: left;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
}

.table tr {
  transition: background-color 0.2s;
}

.table tr:hover {
  background-color: #f8f9fa;
}

.table td {
  border-top: 1px solid #e9ecef;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.pagination-buttons {
  display: flex;
  align-items: center;
}

.page-info {
  color: #495057;
  font-size: 14px;
}

.page-jump {
  margin-left: 15px;
  padding-left: 15px;
  border-left: 1px solid #e9ecef;
}

.page-input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  text-align: center;
}

.page-input:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.empty-message {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8fafc;
  border-radius: 6px;
  border: 1px dashed #e2e8f0;
}

.empty-message i {
  color: #28a745;
  margin-bottom: 15px;
}

.empty-message h4 {
  color: #1e293b;
  margin-bottom: 8px;
}

.empty-message p {
  color: #64748b;
  margin: 0;
}

/* 新增：移动端适配样式 */
.d-none {
  display: none !important;
}

.mobile-btn {
  padding: 4px 8px !important;
  font-size: 12px !important;
}

.operation-cell {
  white-space: nowrap; /* 防止按钮换行 */
}

/* 响应式调整（增强版） */
@media (max-width: 768px) {
  .submit-review-container {
    padding: 10px !important;
  }

  .header {
    padding: 10px !important;
    margin-bottom: 15px !important;
  }

  .card-body {
    padding: 15px !important;
  }

  .table th,
  .table td {
    padding: 8px 10px !important;
    font-size: 13px !important;
  }

  .btn-view {
    margin-left: 4px !important;
  }

  .pagination {
    flex-direction: column !important;
    align-items: flex-start !important;
  }

  .pagination-controls {
    width: 100% !important;
    justify-content: space-between !important;
    margin-top: 10px !important;
  }

  .page-jump {
    margin-left: 0 !important;
    padding-left: 0 !important;
    border-left: none !important;
  }

  .empty-message {
    padding: 30px 10px !important;
  }

  /* 表格横向滚动优化 */
  .contracts-table {
    -webkit-overflow-scrolling: touch; /* 移动端平滑滚动 */
  }
}
</style>